package com.zhoutao123.hephaestus.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhoutao123.hephaestus.object.bussiness.VBlog;
import com.zhoutao123.hephaestus.object.bussiness.VBlogs;
import com.zhoutao123.hephaestus.object.exception.NotFountException;
import com.zhoutao123.hephaestus.object.transport.ArticleUpdate;
import com.zhoutao123.hephaestus.object.transport.BlogTO;
import com.zhoutao123.hephaestus.object.transport.PageBean;
import com.zhoutao123.hephaestus.repository.entity.Blog;
import com.zhoutao123.hephaestus.repository.entity.BlogExample;
import com.zhoutao123.hephaestus.service.AbstractService;
import com.zhoutao123.hephaestus.service.BlogLookService;
import com.zhoutao123.hephaestus.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class BlogServiceImpl extends AbstractService implements BlogService {

  @Autowired private BlogLookService blogLookService;

  @Override
  public VBlog getById(String blogId, Boolean withAttachment) {
    Blog blog = blogMapper.selectByPrimaryKey(blogId);
    if (blog == null) {
      throw new NotFountException("获取失败,文章没有发现");
    }
    VBlog vBlog = VBlog.of(blog);
    if (withAttachment) {
      vBlog.setVBlogLookCount(blogLookService.getLookCountByBlogId(blogId));
    }
    return vBlog;
  }

  @Override
  public VBlogs getByPageInfo(String key, PageBean pageInfo) {
    BlogExample example = new BlogExample();
    BlogExample.Criteria criteria = example.createCriteria();
    if (StringUtils.hasText(key)) {
      criteria.andTitleLike("%" + key + "%");
    }
    example.setOrderByClause("create_time DESC");
    PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
    List<Blog> blogList = blogMapper.selectByExample(example);
    PageInfo<Blog> page = new PageInfo<>(blogList);
    VBlogs vBlogs = VBlogs.of(page);
    vBlogs
        .getList()
        .forEach(
            vBlog -> {
              vBlog.setVBlogLookCount(blogLookService.getLookCountByBlogId(vBlog.getId()));
            });
    return vBlogs;
  }

  @Override
  public VBlog updateById(String articleId, ArticleUpdate update) {
    return null;
  }

  @Override
  public VBlogs getLatestWithParam(Integer number) {
    PageBean pageInfo = new PageBean();
    pageInfo.setPageNum(1).setPageSize(number);
    return getByPageInfo(null, pageInfo);
  }

  @Override
  public VBlog createOrUpdateBlog(BlogTO blogTO) {
    Blog blog = blogTO.toEntity();
    if (StringUtils.hasText(blogTO.getId())) {
      blogRepo.updateByConditionSelective(blog, criteria -> criteria.andIdEqualTo(blogTO.getId()));
    } else {
      blogRepo.insertSelective(blog);
    }
    return getById(blog.getId(), false);
  }
}
